package com.lxf.web;

import com.lxf.bean.Student;
import com.lxf.service.Impl.StudentServiceImpl;
import com.lxf.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/Educational/student/getStudentList")
public class GetStudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取参数
        //1.1、模糊查询条件
        String username = req.getParameter("username");
        String stuno = req.getParameter("userid");
        String sex = req.getParameter("sex");
        System.out.println("前端数据username:" + username + "stuno:" + stuno + "sex:" + sex);
        int sexNum = -1;
        try {
            sexNum = Integer.parseInt(sex);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //1.2、分页数据 开始位置 显示条数
        String pageIndex = req.getParameter("pageIndex");
        System.out.println("pageIndex:" + pageIndex);
        //如果页面没有传入pageIndex的值，默认查询第一页
        int index = (pageIndex == null || pageIndex == "" ? 1 : Integer.parseInt(pageIndex));

        //2、调取service层
        StudentService studentDao = new StudentServiceImpl();
        List<Student> list = studentDao.getStudents(username, stuno, sexNum, index, 5);
        System.out.println("调取了Serverlet");
        //获取总页数=总条数%每页显示的条数>0?总条数/每页显示条数
        int total = studentDao.total(username, stuno, sexNum);
        int totalPages = total % 5 > 0 ? total / 5 + 1 : total / 5;
        System.out.println("总条数：" + total + "--总页数：" + totalPages);
        //3、跳转页面
        //如果后台想给前台传数据  一定要后台存值
        req.setAttribute("list", list);
        req.setAttribute("username", username);
        req.setAttribute("userno", stuno);
        req.setAttribute("sex", sexNum);
        req.setAttribute("index", index);
        req.setAttribute("total", total);
        req.setAttribute("totalPages", totalPages);
        req.setAttribute("size", 5);
        req.getRequestDispatcher("list.jsp").forward(req, resp);


    }
}
